<?php

require_once 'constants.php';

function image_resize($path, $max_dimensions = array(800,600), $flip_sizes = true) {
	$extensions = array("gif","jpg","bmp","png");
	$max_dimensions = (is_array($max_dimensions) && count($max_dimensions)==2) ? $max_dimensions : array(800,600);
	if(file_exists($path)) {
		$ext = strtolower(substr($path, strrpos($path,".")+1));
		$ext_eval = $ext=="jpg" ? "jpeg" : $ext;
		$rgx = '/\.'.implode('$|\.', $extensions).'$/i';
		
		if(preg_match($rgx,$path)) {
			eval('$img = imagecreatefrom'.$ext_eval.'(\''.$path.'\');');
			if($img) {
				$width = imagesx($img); 
				$height = imagesy($img);
				$width1 = $width; $height1 = $height;
				
				if($flip_sizes && $height>$width) {
					$max_dimensions = array_reverse($max_dimensions);
				}
				
				if($height > $max_dimensions[1]) {
					$width = $max_dimensions[1]*$width/$height;
					$height = $max_dimensions[1];
				}
				if ($width > $max_dimensions[0]) {
					$height = $max_dimensions[0]*$height/$width;
					$width = $max_dimensions[0];
				}
				$img2 = imagecreatetruecolor($width,$height);
				imagecopyresized($img2,$img,0,0,0,0,$width,$height,$width1,$height1);
				
				eval('image'.$ext_eval.'($img2,$path);');
			}
		}
	}
}

function emptydir($dirname) {
	$dirname = preg_replace('/\/+$/',"",$dirname)."/";
	if (is_dir($dirname)) {
		$dir = opendir($dirname);
		while ($f = readdir($dir)) {
			if(!preg_match('/^\.+$/',$f) && !is_dir($dirname.$f)) {
				$ret = unlink($dirname.$f);
				echo $dirname.$f." - ".($ret?1:0)."<br />";
			}
		}
	}
}

function _dump($var){
	echo '<pre class="debug">';
	if(is_array($var) || is_object($var)){
		print_r($var);
	}elseif(is_null($var) || is_bool($var)){
		var_dump($var);
	}else{
		echo $var;
	}
	echo "</pre>";
}

function isempty(&$var,$defval=null){
	if(empty($var)){
		$var = $defval;
	}
}

function getFromInput($name) {
	return isset($_REQUEST[$name]) ? $_REQUEST[$name] : null;
}

function strtotitle($str){
	return strtoupper(substr($str,0,1)).strtolower(substr($str,1));
}

function unpretty($str) {
	$str = str_replace("_"," ",$str);
	return $str;
}

function redirect($url) {
	if (preg_match('/^\//',$url)) {
		$url = ROOT.$url;
	}
	header("Location: $url");
}

function pager(&$object,$page=1,$sum=0) {
	$num_pages = ceil($sum/ITEMS_PER_PAGE);
	$num_pager_items = $num_pages>PAGER_LENGTH ? PAGER_LENGTH : $num_pages;
	
	$start = $page;
	$loop = $num_pages+1;
	
	$start = $start>$num_pages ? $num_pages : $start;
	$start = ($loop-$start)<PAGER_LENGTH ? $loop-PAGER_LENGTH : $start;
	$start = $start<1 ? 1 : $start;
	
	$object->assign("start",$start);
	$object->assign("loop",$loop);
	$object->assign("max_links",PAGER_LENGTH);
}

?>